package com.queclink.ycm.entity.data;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.queclink.ycm.common.utils.HexUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * @author jim.li
 * @email jim.li@queclink.com
 * @date 2021-12-27 11:20:00
 */
public class Data88 extends Data {

    private String IMSI;
    private String ICCID;

    private String SIMCardStatus;

    @JSONField(
            name = "IMSI"
    )
    public String getIMSI(JSONObject jsonObject) {
        StringBuffer sb = new StringBuffer();
        String imsi = jsonObject.getString("IMSI");
        sb.append(imsi);
        while (sb.length() < 16) {
            sb.insert(0, "0");
        }
        return sb.toString();
    }

    public void setIMSI(String iMSI) {
        this.IMSI = iMSI;
    }

    @JSONField(
            name = "ICCID"
    )
    public String getICCID(JSONObject jsonObject) {
        if (!jsonObject.containsKey("ICCID") || StringUtils.isEmpty(jsonObject.getString("ICCID"))) {
            return "FF00";
        } else {
            StringBuffer sb = new StringBuffer();
            String iccid = jsonObject.getString("ICCID");
            sb.append(iccid);
            while (sb.length() < 20) {
                sb.insert(0, "0");
            }
            return sb.toString();
        }
    }

    @JSONField(
            name = "SIMCardStatus"
    )
    public String getSIMCardStatus(JSONObject jsonObject) {
        Integer simCardStatus = jsonObject.getInteger("SIMCardStatus");
        if (ObjectUtils.isEmpty(simCardStatus)) {
            return "00";
        }
        return HexUtils.intToHex(simCardStatus, 2);
    }

    public void setICCID(String iCCID) {
        this.ICCID = iCCID;
    }

    public String getDataID() {
        // data88
        return HexUtils.intToHex(88, 2);
    }

    public String getLength() {
        return "17";
    }

    @Override
    public String combine(JSONObject jsonObject) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append(this.getIMSI(jsonObject));
        sb.append(this.getICCID(jsonObject));
//        if (jsonObject.containsKey("SIMCardStatus")) {
            sb.append("00000000");
            sb.append(this.getSIMCardStatus(jsonObject));
//        }

        int len = sb.length();
        len = len / 2;
        if (len > 127) {
            sb.insert(0, HexUtils.intToHex(len, 4));
        } else {
            sb.insert(0, HexUtils.intToHex(len, 2));
        }
        sb.insert(0, this.getDataID());
        return sb.toString();
    }
}
